package com.example.java_chatroom.controller;


import com.example.java_chatroom.model.Friend;
import com.example.java_chatroom.model.FriendMapper;
import com.example.java_chatroom.model.User;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/friend")
public class FriendController {
    @Resource
    private FriendMapper friendMapper;

    @GetMapping("/friendList")
    public List<Friend> getFriendList(HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        //如果获取失败则返回一个空的列表
        if (session == null) {
            System.out.println("[getFriendList] session不存在！");
            return new ArrayList<Friend>();
        }

        User user = (User)session.getAttribute("user");
        if (user == null) {
            System.out.println("[getFriendList] user不存在");
            return new ArrayList<Friend>();
        }

        //返回好友列表
        return friendMapper.selectFriendListByUserId(user.getUserId());
    }

    @PostMapping("/delFriend")
    public int delFriend(int friendId, HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        if (session == null) {
            System.out.println("[delFriend] session不存在!");
            return -1;
        }
        User user = (User)session.getAttribute("user");

        // 根据当前登录用户的id和好友id去删除数据库中的记录
        int i = 0;
        // 两个好友分别将对方删除
        i += friendMapper.delFriendByFriendId(user.getUserId(), friendId);
        i += friendMapper.delFriendByFriendId(friendId, user.getUserId());
        System.out.println("删除好友成功！ 影响行数："+i);
        return i;
    }
}
